-- UIOldTv
-- Created by chengb Sep/23/2015
-- 老式电视机

UIOldTv = class("UIOldTv", function()
    return cc.Layer:create();
end);

function UIOldTv.create(gridData)
    return UIOldTv.new(gridData);
end

-- 构造函数
-- @param gridData : 格子数据（仅在迷宫中需要传入）
function UIOldTv:ctor(gridData)
    self:setName("UIOldTv");
    local node = cc.CSLoader:createNode("layout/ad/OldTv.csb");
    self:addChild(node);
    self.node = node;

    if DungeonM.isInDungeon() then
        assert(type(gridData) == "table", "迷宫中必须传入格子数据！");

        self.gridData = gridData;
        self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);
    end

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIOldTv:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 重绘
function UIOldTv:redraw()
    local titleLabel = findChildByName(self.node, "CT/title_node/title");
    local iconImg    = findChildByName(self.node, "CT/icon");
    local descLabel  = findChildByName(self.node, "CT/desc");
    local desc2Label = findChildByName(self.node, "CT/desc2");
    local btnOk      = findChildByName(self.node, "CT/btn_ok");

    local title     = "";
    local desc      = "";
    local iconPath  = "";
    local okBtnText = "";

    if self.gridData then
        -- 迷宫中

        local class = self.gridData.class;
        local buildingInfo = BuildingBonusM.queryBuildingView(class);

        -- 标题
        title = buildingInfo["title"];

        -- 图标
        iconPath = getLevelItemIconPath(buildingInfo["icon"]);

        -- 描述
        desc = buildingInfo["dialog"] or "";

        -- 计算收看广告奖励
        local bonus = self.gridData.bonus;
        local attrib = bonus[2];
        local value  = bonus[3];
        if string.match(desc, "{attrib}") ~= nil then
            desc = string.gsub(desc, "{attrib}", FieldsM.getFieldName(attrib));
        end
        if string.match(desc, "{value}") ~= nil then
            desc = string.gsub(desc, "{value}", value);
        end

        -- 确定按钮文本
        okBtnText = buildingInfo["view_text"];
        iconImg:setScale(1.3);
    else
        -- 迷宫外
        local bonus = AdM.calcMarketAdBonus();
        local attrib = bonus[2];
        local value  = bonus[3];
        title = getLocStr("slime_tv_title");
        iconPath = "images/ui/market/tv2.png";
        desc = string.format(getLocStr("slime_tv_desc"), value, FieldsM.getFieldName(attrib));
        okBtnText = getLocStr("btn_text_watch_ad");
        iconImg:setScale(1.1);
    end

    -- 计算点击广告的奖励
    local extraBonus = AdM.calcAdClickBonus();
    local attrib = extraBonus[2];
    local value  = extraBonus[3];

    -- 额外描述
    local desc2 = string.format(getLocStr("slime_tv_extra_desc"), value, FieldsM.getFieldName(attrib));

    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, kerning);
    titleLabel:setString(title);
    convertTextToArtWord(titleLabel, "images/ui/text_mask/text_mask2.png");
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOk:setTitleText(okBtnText);
    iconImg:loadTexture(iconPath);
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, false, kerning2);
    TextStyleM.setTextStyle(desc2Label, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, false, kerning2);
    applyString(descLabel, desc);
    applyString(desc2Label, desc2);
end

-- 注册点击事件
function UIOldTv:registerTouchEvent()
    -- 注册返回按钮点击事件
    local node = self.node;
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIOldTv");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册确定按钮点击事件
    local btnOk = findChildByName(node, "CT/btn_ok");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_select");
            
            if self.gridData then
                -- 如果在迷宫中，需要记录电视机的位置，等播放完毕后再处理
                AdM.setTvPos(self.gridData:getPos());
            end

            -- 请求播放广告
            playAwardAd();
            
            if UIMgr.getCurrentScene():isOpen("UIMarketMain") then
                -- 隐藏商城界面的广告入口
                -- 注：当下一条广告准备完毕时，会再次通知其显示
                local uiMarket = UIMgr.getCurrentScene():getFormByName("UIMarketMain");
                uiMarket:hideAdEntry();
                
                -- 这里需要先预增加播放次数，原因如下：
                -- 如果在收看广告期间，下一条广告已经加载完毕，这时候可能会将电视机图标显示出来，可实际上玩家已经没有收看次数了
                AdM.preAddPlayTimes();
            end
            
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIOldTv");
        end
    end
    AddTouchEventListener(btnOk, onOkClick);
end

-- 注册事件处理回调函数
function UIOldTv:registerEventCallback()
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIOldTv 界面析构清理");
            EventMgr.removeAll("UIOldTv");

            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():showMenu();
            end

        elseif eventType == "enter" then
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():hideMenu();
            end
        end
    end);
end







